// pages/releaseAct/releaseAct.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formlist: [
      { isrequire: true, value: '', label: '活动类型', valueType: 'text', key: 'typeName', tips: '请选择', type: 'select', rangKey:'name',data: []},
      { isrequire: true, value: '', label: '活动名称', valueType: 'text', key: 'name', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '活动地点', valueType: 'text', key: 'place', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '活动费用', valueType: 'digit', key: 'fee', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '人 数', valueType: 'number', key: 'maxNumbers', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '开始日期', valueType: 'text', key: 'startDate', tips: '请选择', type: 'date',mode:'date' },
      { isrequire: true, value: '', label: '开始时间', valueType: 'text', key: 'startTime', tips: '请选择', type: 'date', mode: 'time' },
      { isrequire: true, value: '', label: '结束日期', valueType: 'text', key: 'endDate', tips: '请选择', type: 'date', mode: 'date' },
      { isrequire: true, value: '', label: '结束时间', valueType: 'text', key: 'endTime', tips: '请选择', type: 'date', mode: 'time' }
    ],	   
    formData: {
      // addActivity:'',
      name: '',
      typeId: '',
      place: '',
      userId: '',
      fee: '',
      description: '', 
      activityImgUrl: '', 
      maxNumbers: '', 
      startDate: '', 
      endDate: '',
      startTime:"",
      endTime:''
    },
    show:{
      activityImgUrl:''
    },
    typeName:'',
    inputShow: '',
    canSubmit: false,
    userInfo: '',
    curren_date: app.formDate(new Date()).split(" ")[0],
    canSubmit:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var key = 'formData.userId';
    if(options.id != undefined){
      this.setData({
        ['formData.typeId']: options.id,
        typeName: options.label
      })
    }
    this.setData({
      [key]: JSON.parse(wx.getStorageSync('userInfo')).id,
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    this.getAllType()
  },
  //查询所有活动分类
  getAllType: function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar +'tGyActivityType/all', 
      data: {},
      header: {
         'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        let key = 'formlist[0].data';
        _this.setData({
          [key]: res.data.data
        })
        _this.data.formlist[0].data = res.data.data;
      }
    })
  },
  bindPickerChange: function (e) {
    var item = e.target.dataset.item;
    var oIndex = e.detail.value;
    if (e.target.dataset.type != undefined) {
      this.data.formData[item.key] = e.detail.value;
    }
    else {
      this.data.formData.typeId = item.data[oIndex].id;
      this.setData({
        [item.key]: this.data.formlist[e.target.dataset.index].data[e.detail.value].name,
      })
    }
    this.setData({
      formData: this.data.formData
    });
    this.changeValue();
  },
  bindFormSubmit: function (e) {
    var item = this.data.currentInput;
    var flag = true;
    if (this.data.active != '') {
      if (item.reg) {
        var reg = new RegExp(item.reg);
        // var reg = item.reg;
        if (!reg.test(e.detail.value.con)) {
          flag = false;
          this.setData({
            'modelData.showModal': true,
            'modelData.content': '请输入正确的' + item.label
          })
        }
      }
      if (flag) {
        this.data.inputShow = false;
        this.data.formData[item.key] = e.detail.value.con;
        // wx.setNavigationBarTitle({
        //   title: '入驻商家'
        // })
        this.setData({
          inputShow: this.data.inputShow,
          value: '',
          formData: this.data.formData
        })
      }
    }
  },
  //输入框点击事件
  inputTap(e) {
    var item = e.currentTarget.dataset.item;
    this.data.inputShow = true;
    this.data.value = this.data.formData[item.key];
    if (this.data.formData[item.key] == '' && item.isrequire) {
      this.data.active = '';
    } else {
      this.data.active = 'active';
    }
    wx.setNavigationBarTitle({
      title: item.label
    })
    this.setData({
      inputShow: this.data.inputShow,
      value: this.data.value,
      currentInput: item,
      active: this.data.active
    })
    this.changeValue()
  },
  changeValue: function () {
    var flag = true;
    var item = this.data.formData;
    if ((item.name == '') || (item.typeId == '') || (item.place == '') || (item.userId == '') || (item.fee == '') || (item.description == '') || (item.activityImgUrl == '') || (item.maxNumbers == '') || (item.startTime == '') || (item.endTime == '')) {
      flag = false;
    }
    this.setData({
      canSubmit: flag
    })
  },
  bindDateChange:function(e){
    this.data.formData[e.currentTarget.dataset.ind].value = e.detail.value;
    this.setData({
      formData: this.data.formData
    })
    this.changeValue();
  },
  uploadImg:function(e){

    var that=this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.data.formData[e.currentTarget.dataset.key] = res.tempFilePaths[0];
        that.uploadImgFunc(that, tempFilePaths);
      }
    })
  },
  /*上传图片*/
  uploadImgFunc: function (page, path) {
    var that = this;
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    }),
      wx.uploadFile({
        url: app.globalData.httpApiCar + 'uploadfile/upload1',
        filePath: path[0],
        name: 'file',
        header: { "Content-Type": "multipart/form-data" },
        formData: {},
        success: function (res) {
          var data = JSON.parse(res.data);
          if (data.success) {
            wx.hideToast();  //隐藏Toast
            let key = 'formData.activityImgUrl';
            let key1 = 'show.activityImgUrl';
            that.setData({
              [key]: data.data,
              [key1]: app.globalData.httpApiImg + data.data
            })
          }
          else{
            wx.showModal({
              title: data.error,
              content: '上传失败',
              showCancel: false
            })
          }

        }
      })
    this.changeValue();
  },
  changeTextarea:function(e){
    this.data.formData.description=e.detail.value;
    this.setData({ formData: this.data.formData });
    this.changeValue();
  },
  bindInputFunc: function (e) {
    let key = e.currentTarget.dataset.key;
    let types = e.currentTarget.dataset.type;
    types == 'digit'?this.data.formData[key] = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'):this.data.formData[key] = e.detail.value;
    this.setData({ formData: this.data.formData });
    this.changeValue();
  },
  submit:function(e){
    var param={};
    for (var j in this.data.formData){
      if (j != 'startDate' && j != 'endDate'){
        param[j] = this.data.formData[j];
      }
    }
    param.startTime = this.data.formData.startDate+' '+this.data.formData.startTime;
    param.endTime = this.data.formData.endDate+' ' +this.data.formData.endTime;
    var end = new Date(param.endTime.replace(/-/g, "/")).getTime();
    var start = new Date(param.startTime.replace(/-/g, "/")).getTime();
    if (this.data.canSubmit){
      if (start > end) {
        wx.showToast({
          title: '结束时间不能早于开始时间',
          icon: 'none',
          duration: 2000
        })
      }
      else{
        wx.showLoading({
          title: '发布中',
        })
        wx.request({
          url: app.globalData.httpApiCar + 'tGyActivity/save',
          data: param,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: function (res) {
            wx.hideLoading();
            if (res.data.success) {
              wx.setStorage({
                key: 'url',
                data: '/pages/activity/activity',
              })
              wx.redirectTo({
                url: '/pages/regsuccess/regsuccess?btnText=返回首页&showText=发布成功'
              })
            }
            else{
              wx.showToast({
                title: res.data.error,
                icon: 'none',
                duration: 2000
              })
            }

            // wx.navigateBack()
          }
        })
      }
      
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.getAllType()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})